package com.microservice.user.controller;

import com.microservice.api.common.PageResult;
import com.microservice.api.common.Result;
import com.microservice.api.wechat.ArticleServiceClient;
import com.microservice.api.wechat.dto.ArticleDTO;
import com.microservice.api.wechat.dto.ArticleReviewRecordDTO;
import com.microservice.api.wechat.dto.UserBindConfigDTO;
import com.microservice.common.util.MailUtil;
import com.microservice.common.utils.AuthUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户文章接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class UserArticleController {

    @Resource
   private ArticleServiceClient articleServiceApi;
    @Autowired
    MailUtil mailUtil;

    @GetMapping("/review/records/{articleId}")
    public Result getReviewRecords(@PathVariable Long articleId){
        return articleServiceApi.getReviewRecords(articleId);
    }


    /**
     * 根据用戶ID查询綁定的公衆號
     *
     * @param id 用戶ID
     * @return 賬號信息
     */
    @GetMapping("/getUserBindAccount/{id}")
    Result<List<UserBindConfigDTO>> getUserBindAccount(@PathVariable("id") Long id){
        Result<List<UserBindConfigDTO>> userBindConfigDTOS =articleServiceApi.getUserBindAccount(id);
        if(userBindConfigDTOS.getData().size()>1){
            return articleServiceApi.getUserBindAccount(id);
        }else{
            return Result.success(null);
        }

    }

    /**
     * 保存文章（自动关联当前登录用户）
     */
    @PostMapping("/save")
    public Result<ArticleDTO> save(@RequestBody ArticleDTO article) {
        try {
            // 自动获取当前登录用户ID并设置到文章
            Long currentUserId = AuthUtils.requireUserId();
            article.setUserId(String.valueOf(currentUserId));
            article.setAuthor(AuthUtils.getCurrentNickname());
            log.info("用户 {} (ID:{}) 保存文章", AuthUtils.getCurrentNickname(), currentUserId);
            return articleServiceApi.save(article);
        } catch (Exception e) {
            log.error("保存文章失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新文章（只能更新自己的文章）
     */
    @PutMapping("/save")
    public Result<ArticleDTO> update(@RequestBody ArticleDTO article) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = AuthUtils.requireUserId();
            
            // 查询文章验证所有权
            Result<ArticleDTO> articleResult = articleServiceApi.getById(article.getId());
            if (articleResult.getCode() != 200 || articleResult.getData() == null) {
                return Result.error("文章不存在");
            }
            
            ArticleDTO existingArticle = articleResult.getData();
            if (!String.valueOf(currentUserId).equals(existingArticle.getUserId())) {
                log.warn("用户 {} 尝试修改其他用户的文章 {}", currentUserId, article.getId());
                return Result.error("无权修改他人的文章");
            }
            
            log.info("用户 {} (ID:{}) 更新文章 {}", AuthUtils.getCurrentUsername(), currentUserId, article.getId());
            return articleServiceApi.update(article);
        } catch (Exception e) {
            log.error("更新文章失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 提交审核（只能提交自己的文章）
     */
    @GetMapping("/check/{articleId}")
    public Result<String> submitForReview(@PathVariable Long articleId) {
        try {
            Long currentUserId = AuthUtils.requireUserId();
            
            // 验证文章所有权
            Result<ArticleDTO> articleResult = articleServiceApi.getById(articleId);
            if (articleResult.getCode() != 200 || articleResult.getData() == null) {
                return Result.error("文章不存在");
            }
            
            if (!String.valueOf(currentUserId).equals(articleResult.getData().getUserId())) {
                log.warn("用户 {} 尝试提交他人文章审核", currentUserId);
                return Result.error("无权操作他人的文章");
            }
            
            log.info("用户 {} 提交文章 {} 审核", currentUserId, articleId);
            //同一用户超过阈值提交忽略邮件
            String html = String.format("""
                <html>
                <body>
                    <h2>新文章待审核</h2>
                    <p><strong>文章标题：</strong>%s</p>
                    <p><strong>作者：</strong>%s</p>
                    <p><a href="http://your-domain.com/admin/review" 
                          style="background-color: #4CAF50; color: white; 
                                 padding: 10px 20px; text-decoration: none;">
                        立即审核
                    </a></p>
                </body>
                </html>
                """, articleResult.getData().getTitle(), articleResult.getData().getAuthor());
            mailUtil.sendSimpleMailAsync(articleResult.getData().getUserId(),"wang_haoge0916@163.com","你有一条新的文章需要审核！",html);
            return articleServiceApi.updateStatus(articleId, 1);
        } catch (Exception e) {
            log.error("提交审核失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 撤回审核（只能撤回自己的文章）
     */
    @GetMapping("/returnCheck/{articleId}")
    public Result<String> returnCheck(@PathVariable Long articleId) {
        try {
            Long currentUserId = AuthUtils.requireUserId();
            
            // 验证文章所有权
            Result<ArticleDTO> articleResult = articleServiceApi.getById(articleId);
            if (articleResult.getCode() != 200 || articleResult.getData() == null) {
                return Result.error("文章不存在");
            }
            
            if (!String.valueOf(currentUserId).equals(articleResult.getData().getUserId())) {
                log.warn("用户 {} 尝试撤回他人文章审核", currentUserId);
                return Result.error("无权操作他人的文章");
            }
            
            log.info("用户 {} 撤回文章 {} 审核", currentUserId, articleId);
            return articleServiceApi.updateStatus(articleId, 0);
        } catch (Exception e) {
            log.error("撤回审核失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除文章（只能删除自己的文章）
     */
    @DeleteMapping("/deleteArticle/{articleId}")
    public Result<String> deleteArticle(@PathVariable Long articleId) {
        try {
            Long currentUserId = AuthUtils.requireUserId();
            
            // 验证文章所有权
            Result<ArticleDTO> articleResult = articleServiceApi.getById(articleId);
            if (articleResult.getCode() != 200 || articleResult.getData() == null) {
                return Result.error("文章不存在");
            }
            
            if (!String.valueOf(currentUserId).equals(articleResult.getData().getUserId())) {
                log.warn("用户 {} 尝试删除他人文章 {}", currentUserId, articleId);
                return Result.error("无权删除他人的文章");
            }
            
            log.info("用户 {} 删除文章 {}", currentUserId, articleId);
            return articleServiceApi.delete(articleId);
        } catch (Exception e) {
            log.error("删除文章失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询我的文章（自动查询当前用户的文章）
     */
    @GetMapping("/page")
    public Result<PageResult<ArticleDTO>> page(
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "status", required = false) Integer status) {
        try {
            // 自动获取当前用户ID，只查询自己的文章
            Long currentUserId = AuthUtils.requireUserId();
            String userId = String.valueOf(currentUserId);
            
            log.info("用户 {} 查询自己的文章列表", currentUserId);
            return articleServiceApi.listByUserId(userId,status,current, size );
        } catch (Exception e) {
            log.error("查询文章列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户的文章统计信息
     * 统计已通过审核的文章数量和所有文章的总浏览量
     */
    @GetMapping("/statistics")
    public Result getUserStatistics() {
        try {
            // 自动获取当前登录用户ID
            Long currentUserId = AuthUtils.requireUserId();
            log.info("用户 {} 查询统计信息", currentUserId);
            return articleServiceApi.getUserStatistics(currentUserId);
        } catch (Exception e) {
            log.error("获取用户统计信息失败", e);
            return Result.error(e.getMessage());
        }
    }

}
